package edu.whu.demo.service;

import edu.whu.demo.dao.UserRepository;
import edu.whu.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class UserService {
    @Autowired
    private UserRepository repository;

    @Cacheable(cacheNames = "user", key = "#name", condition = "#name!=null")
    public User getUser(String name) {
        Optional<User> u = repository.findById(name);
        return u.isPresent()?u.get():null;
    }

    @CacheEvict(cacheNames = "user", key = "#username")
    public void deleteUser(String userName) {
        repository.deleteById(userName);
    }

    @CacheEvict(cacheNames = "user", key = "#name")
    public User updateUser(String name, User user) {
        if(name == null || !name.equals(user.getName()) || repository.findById(name).isPresent()) {
            throw new RuntimeException("update error");
        }
        return repository.saveAndFlush(user);
    }

    public List<User> findAll() {return repository.findAll();}

    public User addUser(User user) {
        return repository.save(user);
    }
}
